﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;
using Telerik.Web.UI;

public partial class Shared_UserControl_AsyncUploadEx : UserControl
{
    /// <summary>
    /// 保存所有文件
    /// </summary>
    /// <returns></returns>
    public string SaveFiles()
    {
        if (raUpload.UploadedFiles.Count > 0)
        {
            List<string> uploadedFiles = new List<string>(raUpload.UploadedFiles.Count);
            string fileName = string.Empty;
            foreach (UploadedFile file in raUpload.UploadedFiles)
            {
                fileName = SaveFile(file);
                uploadedFiles.Add(fileName);
            }
            return string.Join(",", uploadedFiles.ToArray());
        }
        return string.Empty;
    }

    /// <summary>
    /// 保存单个文件返回相对路径
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    string SaveFile(UploadedFile file)
    {
        string uploadFullName = GetUploadFullName(file.FileName);
        string absoluteFullName = Path.Combine(AbsoluteFileSavePath, uploadFullName);//转换为本地路径
        CheckDirectoryExists(absoluteFullName);
        file.SaveAs(absoluteFullName);
        return FileSavePath + uploadFullName;
    }

    /// <summary>
    /// 检查目录是否存在
    /// 不存在就创建，并把名称加入缓存
    /// </summary>
    /// <param name="absolutePath"></param>
    void CheckDirectoryExists(string absolutePath)
    {
        string absoluteFullPath = Path.GetDirectoryName(absolutePath);
        if (DirectoryCache.Contains(absoluteFullPath))
            return;

        if (!Directory.Exists(absoluteFullPath))
            Directory.CreateDirectory(absoluteFullPath);
        DirectoryCache.Add(absoluteFullPath);
    }

    /// <summary>
    /// 生成文件名
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    string GetUploadFullName(string filename)
    {
        if (extensions == null)
            extensions = new List<string>(raUpload.AllowedFileExtensions);
        if (string.IsNullOrEmpty(AbsoluteFileSavePath))
            AbsoluteFileSavePath = Server.MapPath("~" + FileSavePath);

        //当前扩展名存储的路径,第7个开始为文件
        string extDir = extensions.IndexOf(Path.GetExtension(filename).Substring(1)) < 7 ? "mpic/" : "mfile/";
        string todayDir = DateTime.Now.ToString("yyyy/MM/dd") + "/";//按日期保存
        string fullNameWithoutRoot = string.Empty;//文件存储路径，不包括根路径
        string prefix = "0-";
        while (string.IsNullOrEmpty(fullNameWithoutRoot) || File.Exists(Path.Combine(AbsoluteFileSavePath, fullNameWithoutRoot)))
        {
            if (!string.IsNullOrEmpty(fullNameWithoutRoot))
            {//处理重复的文件名
                if (reFileName.IsMatch(filename))
                {
                    int num = int.Parse(reFileName.Match(filename).Result("$1")) + 1;
                    filename = num.ToString() + filename.Substring(1);
                }
                else
                {
                    filename = prefix + filename;
                }
            }
            fullNameWithoutRoot = extDir + todayDir + filename;
        }

        return fullNameWithoutRoot;
    }

    static List<string> extensions;
    static Regex reFileName = new Regex("^(\\d)-", RegexOptions.Compiled);
    static string FileSavePath = "/upload/";
    static string AbsoluteFileSavePath;
    static readonly List<string> DirectoryCache = new List<string>();//目录名称缓存
}